package main.flex.manager.section
{
	import flash.events.Event;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.SyncEvent;
	import flash.media.Camera;
	import flash.media.Microphone;
	import flash.media.Video;
	import flash.net.NetStream;
	import flash.net.Responder;
	import flash.net.SharedObject;
	import flash.system.Security;
	import flash.system.SecurityPanel;
	
	import main.flex.connectivity.NetConnectionClient;
	import main.flex.connectivity.NetConnectionManager;
	import main.flex.connectivity.notification.NetConnectionClientEvent;
	import main.flex.utils.CursorHandler;
	import main.flex.widget.section.WiiavieVisioWidget;
	
	import org.servebox.foundry.widget.WidgetManager;

	public class WiiavieVisioWidgetManager extends WidgetManager
	{
		private var nc				:	NetConnectionManager;
		
		private var nsOut			:	NetStream;
		private var nsPlayerOut		:	NetStream;
		private var nsIn1			:	NetStream;
		private var nsPlayerIn1		:	NetStream;
		private var nsIn2			:	NetStream;
		private var nsPlayerIn2		:	NetStream;
		private var nsIn3			:	NetStream;
		private var nsPlayerIn3		:	NetStream;
		
		public var so				:	SharedObject;
		private var _selectedUser	:	Number=0;
		private var _cam			:	Camera;
		
		private var _videoOut		:	Video;
		private var _videoIn1		:	Video;
		private var _videoIn2		:	Video;
		private var _videoIn3		:	Video;
		
        private var _outStream		:	String;
        private var _inStream1		:	String;
        private var _inStream2		:	String;
        private var _inStream3		:	String;
        
		private var _mic			:	Microphone;
		
		private var _uId			:	int;
		private var _uName			:	String;
		
        private var _responder		:	Responder;
        
    	public var currentPosition	:	String;
    	
    	public var _currentUser		:	Array;
    	
		public function WiiavieVisioWidgetManager()
		{
			super();
		}
		
		public function get currentWidget() : WiiavieVisioWidget
		{
			return WiiavieVisioWidget( getWidget() );
		}
		
		[Bindable("userChanged")]
		public function get getCurrentUser() : Array
		{
			return _currentUser;
		}
		
		public function set setCurrentUser( value : Array ) : void
		{
			_currentUser = value;
			dispatchEvent( new Event("userChanged") );
		}
		
		public function init() : void
		{
			CursorHandler.setBusyCursor();
			currentWidget.currentState="chatMode";
			nc = NetConnectionManager.getInstance();
			nc.addEventListener("onConnect", onConnect);
			nc.addEventListener("netStatus", onNCStatus);
			nc.client = NetConnectionClient.getInstance();
			nc.client.addEventListener( NetConnectionClient.ON_USER_ID, onUserID );
			nc.client.addEventListener("onReceiveChatMsg", onReceiveChatMsg);
			
			currentWidget.sendButton.enabled = currentWidget.chatInputText.enabled = false;
			
			var uId : int = _currentUser[0].userId;
			var uName : String = _currentUser[0].name;
			
			nc.createNetConnection( "rtmp://192.168.1.2/viavie/espace" + _currentUser[0].espaceId , uId, uName );
			//nc.createNetConnection( "rtmp://mac-serv.univ-tln.fr/viavie/test/" , uId, uName );
			//nc.createNetConnection( "rtmp://localhost/viavie/espace" + _currentUser[0].espaceId, uId, uName );
		}
		
		private function onConnect(event:NetStatusEvent):void
		{
			currentWidget.chatMsgText.htmlText="<font size='20' family='Verdana'>"+ _currentUser[0].name +" vient de se connecter...</font></br>";
			so = SharedObject.getRemote("userList", nc.uri, false);
			so.addEventListener(SyncEvent.SYNC, onSync);
			so.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSOSecurityErrorEvent);
			so.addEventListener(NetStatusEvent.NET_STATUS, onSONetStatus);
			so.client=this;
			so.connect(nc);
		}
		
		private function onNCStatus(event:NetStatusEvent):void
		{
			switch (event.info.code) {
               case "NetConnection.Connect.Success":
               		_responder=new Responder( streamNow );
                   	nc.call ("streamSelect", _responder);
					break;
			}
		}
		
        private function streamNow (streamSelect:String):void
        {
        	//trace(streamSelect);
            setCam ();
            setMic ();
            setVid ();
             currentPosition=streamSelect;
             switch (streamSelect)
             {
                   case "left" :
                        _outStream="left";
                        _inStream1="right";
                        _inStream2="top";
                        _inStream3="bottom";
                        break;
                   case "right" :
                        _outStream="right";
                        _inStream1="left";
                        _inStream2="top";
                        _inStream3="bottom";
                        break;
                   case "top" :
                        _outStream="top";
                        _inStream1="left";
                        _inStream2="right";
                        _inStream3="bottom";
                        break;
                   case "bottom" :
                        _outStream="bottom";
                        _inStream1="left";
                        _inStream2="top";
                        _inStream3="right";
                        break;
             }

             //Publish local video
            nsOut = new NetStream(nc);
            nsOut.attachAudio( _mic );
            nsOut.attachCamera (_cam);
            nsOut.publish ( _outStream , "live");
            nsPlayerOut = new NetStream(nc);
			nsPlayerOut.play( _outStream );
           	_videoOut.attachNetStream( nsPlayerOut );
			
             //Play streamed video
            nsIn2 = new NetStream(nc);
            nsIn2.attachCamera( _cam );
            nsPlayerIn2 = new NetStream( nc );
           	_videoIn2.attachNetStream( nsPlayerIn2 );
			nsPlayerIn2.play( _inStream1 );
           	
            nsIn1 = new NetStream( nc );
           	nsIn1.attachCamera( _cam );
            nsPlayerIn1 = new NetStream( nc );
           	_videoIn1.attachNetStream( nsPlayerIn1 );
			nsPlayerIn1.play( _inStream2 );
            
            nsIn3 = new NetStream(nc);
           	nsIn3.attachCamera ( _cam );
            nsPlayerIn3 = new NetStream(nc);
           	_videoIn3.attachNetStream( nsPlayerIn3 );
			nsPlayerIn3.play( _inStream3 );
           	
   			CursorHandler.setCustomCursor();

           	
        }
        
        private function setCam ():void
        {
             _cam=Camera.getCamera();
             _cam.setMode (240,180,18);
             _cam.setQuality (0,80);
        }

        private function setMic ():void
        {
             _mic = Microphone.getMicrophone();
             Security.showSettings(SecurityPanel.MICROPHONE);
             _mic.rate=11;
             _mic.setSilenceLevel (12,2000);
        }
        
        private function setVid() :void
        {
			_videoOut = new Video(200,150);
            currentWidget.vidOut.addChild( _videoOut );
			_videoIn1 = new Video(200,150);
            currentWidget.vidRight.addChild( _videoIn1 );
			_videoIn2 = new Video(200,150);
            currentWidget.vidBottom.addChild( _videoIn2 );
			_videoIn3 = new Video(200,150);
            currentWidget.vidLeft.addChild( _videoIn3 );
            
           	currentWidget.vidOut.width=_videoOut.width;
           	currentWidget.vidOut.height=_videoOut.height;
			currentWidget.vidRight.width=_videoIn2.width;
           	currentWidget.vidRight.height=_videoIn2.height;
			currentWidget.vidBottom.width=_videoIn1.width;
           	currentWidget.vidBottom.height=_videoIn1.height;
            currentWidget.vidLeft.width=_videoIn3.width;
           	currentWidget.vidLeft.height=_videoIn3.height;
        }
		
		private function onSync(e:SyncEvent):void
		{
			var usersArray : Array = new Array();
			for (var i:String in so.data){
				usersArray.push({label:so.data[i].userName, data:so.data[i], position:i});
				//trace(i + " : " + so.data[i].userName);
				if(currentPosition=="left"){
					for(var j : Number = 0 ;j<4;j++){
						if(usersArray[j]!=null && usersArray[j].position=="bottom") currentWidget.webcam4.title=usersArray[j].label;
						if(usersArray[j]!=null && usersArray[j].position=="top") currentWidget.webcam2.title=usersArray[j].label;
						if(usersArray[j]!=null && usersArray[j].position=="right") currentWidget.webcam3.title=usersArray[j].label;
						if(usersArray[j]!=null && usersArray[j].position=="left") currentWidget.webcam1.title=usersArray[j].label;
					}
				}else if(currentPosition=="right"){
					for(var k : Number = 0 ;k<4;k++){
						if(usersArray[k]!=null && usersArray[k].position=="bottom") currentWidget.webcam4.title=usersArray[k].label;
						if(usersArray[k]!=null && usersArray[k].position=="top") currentWidget.webcam2.title=usersArray[k].label;
						if(usersArray[k]!=null && usersArray[k].position=="right") currentWidget.webcam1.title=usersArray[k].label;
						if(usersArray[k]!=null && usersArray[k].position=="left") currentWidget.webcam3.title=usersArray[k].label;
					}
				}else if(currentPosition=="top"){
					for(var l : Number = 0 ;l<4;l++){
						if(usersArray[l]!=null && usersArray[l].position=="bottom") currentWidget.webcam4.title=usersArray[l].label;
						if(usersArray[l]!=null && usersArray[l].position=="top") currentWidget.webcam1.title=usersArray[l].label;
						if(usersArray[l]!=null && usersArray[l].position=="right") currentWidget.webcam2.title=usersArray[l].label;
						if(usersArray[l]!=null && usersArray[l].position=="left") currentWidget.webcam3.title=usersArray[l].label;
					}
				}else if(currentPosition=="bottom"){
					for(var m : Number = 0 ;m<4;m++){
						if(usersArray[m]!=null && usersArray[m].position=="bottom") currentWidget.webcam1.title=usersArray[m].label;
						if(usersArray[m]!=null && usersArray[m].position=="top") currentWidget.webcam2.title=usersArray[m].label;
						if(usersArray[m]!=null && usersArray[m].position=="right") currentWidget.webcam4.title=usersArray[m].label;
						if(usersArray[m]!=null && usersArray[m].position=="left") currentWidget.webcam3.title=usersArray[m].label;
					}
				}
				currentWidget.vidOut.width=_videoOut.width;
           		currentWidget.vidOut.height=_videoOut.height;
				currentWidget.vidRight.width=_videoIn2.width;
           		currentWidget.vidRight.height=_videoIn2.height;
				currentWidget.vidBottom.width=_videoIn1.width;
           		currentWidget.vidBottom.height=_videoIn1.height;
            	currentWidget.vidLeft.width=_videoIn3.width;
           		currentWidget.vidLeft.height=_videoIn3.height;
			}
 			if(usersArray.length==1){
				currentWidget.webcam1.visible=true;
				currentWidget.webcam3.visible=false;
				currentWidget.webcam2.visible=false;
				currentWidget.webcam4.visible=false;
			}
			if(usersArray.length==2){
				currentWidget.webcam1.visible=true;
				currentWidget.webcam3.visible=true;
				currentWidget.webcam2.visible=false;
				currentWidget.webcam4.visible=false;
			}
			if(usersArray.length==3){
				currentWidget.webcam1.visible=true;
				currentWidget.webcam3.visible=true;
				currentWidget.webcam2.visible=true;
				currentWidget.webcam4.visible=false;
			}
			if(usersArray.length==4){
				currentWidget.webcam1.visible=true;
				currentWidget.webcam3.visible=true;
				currentWidget.webcam2.visible=true;
				currentWidget.webcam4.visible=true;
			} 
		}
		
		private function onEnterPressed(e:Event):void
		{
			if(currentWidget.chatInputText.text!=""){
				sendTheMessage();
			}
		}
		
		public function onSendButtonClicked():void
		{
			if(currentWidget.chatInputText.text!=""){
				sendTheMessage();
			}
		}
		
		public function sendTheMessage():void
		{
			var msg : String = "<font size='20' color='#99DD00'>" + _currentUser[0].name + " dit : </font><font size='20' color='#000000'>" + currentWidget.chatInputText.text + "</font>";
			
			nc.call("sendChatMessage", null, msg, _selectedUser);
			currentWidget.chatInputText.text="";
		}
		
		[Bindable("onUserId")]
		private function onUserID(e:Event):void
		{
			currentWidget.sendButton.enabled = currentWidget.chatInputText.enabled = true;
		}
		
		private function onReceiveChatMsg(e:NetConnectionClientEvent):void
		{
			var msg:String = e.infoObject.msg;
			currentWidget.chatMsgText.htmlText += msg + "\n";
		}
		
		public function changeViewMode():void
		{
			if(currentWidget.currentState==null){
				currentWidget.currentState="chatMode";
			}else if(currentWidget.currentState=="chatMode"){
				currentWidget.currentState=null;
			}
		}
		
		private function onSONetStatus(event:NetStatusEvent):void
		{
			trace("OnSONetStatus" + event);
		}
		
		private function onSOSecurityErrorEvent(event:SecurityErrorEvent):void
		{
			trace("OnSOSecurityError" + event);
		}
	}
}